<template>
  <!-- 显示当前选择的选项 -->
  <SelectBlock @click="showPicker = true" :text="selectedText" />

  <!-- 弹出 Picker -->
  <van-popup v-model:show="showPicker" round position="bottom">
    <van-picker :columns="options" v-model="selectedValue" @cancel="showPicker = false" @confirm="onConfirm" />
  </van-popup>
</template>

<script>
import { ref, watch } from "vue";
import SelectBlock from "../basic-components/SelectBlock.vue";

/** 支持 按日、按月、按年 选择 */
export default {
  name: "DayMonthPicker",

  props: {
    //让 Vue 就知道这个组件支持 v-model
    modelValue: {
      type: [String, Number, Boolean, Array, Object, null],
      default: null,
    },
  },

  emits: ["update:modelValue", "confirm"],

  components: {
    SelectBlock,
  },

  setup(props, { emit }) {
    // 控制 Picker 显示与隐藏
    const showPicker = ref(false);

    // Picker 的选项
    const options = ref([
      { text: "按日", value: "day" },
      { text: "按月", value: "month" },
      { text: "按年", value: "year" },
    ]);

    // 当前选中的值
    const selectedValue = ref(["month"]);

    // 监听外部传入的 modelValue 并同步
    watch(
      () => props.modelValue,
      (newVal) => {
        if (newVal !== undefined && newVal !== null) {
          selectedValue.value = [newVal];
        }
      },
      { immediate: true }
    );

    // 显示的文本
    const selectedText = ref("按月");

    // 确认选择
    const onConfirm = (value) => {
      // selectedIndexes:[1]
      // selectedOptions:[{text: '按月', value: 'month'}]
      // selectedValues:['month']
      selectedValue.value = value.selectedValues;
      selectedText.value = value.selectedOptions[0]?.text || "";
      showPicker.value = false;

      // 触发事件，将选中的值抛出
      emit("update:modelValue", selectedValue.value[0]);
      emit("confirm", selectedValue.value[0]);
    };

    return {
      showPicker,
      options,
      selectedValue,
      selectedText,
      onConfirm,
    };
  },
};
</script>

<style scoped></style>
